// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

var count = 0, gradesPollTimer, notificationsPollTimer, pollStarted = false;
var settings = {
	"pollingTime" : 15000,
	"notificationTime" : 10000,
	"gradeNotification": "1",
	"notificationNotification": "1",
	"broadcastNotification": "1"
}
setBadge = function () {
	if ( count == 0) {
		chrome.browserAction.setBadgeText({text: ""});
	} else {
		chrome.browserAction.setBadgeText({text: "" + count});
	}
}

getToken = function (username,password) {
    var http = new XMLHttpRequest();
    var url = "http://iportal.g-beehive.com/GucAuth";
    var params = "ChromeExtension," + username + "," + password;
    http.open("POST", url, true);
    http.onreadystatechange = function() {//Call a function when the state changes.
        if(http.readyState == 4 && http.status == 200) {
            console.log(http.responseText);
            if(http.responseText.indexOf("Unauthorized") < 0 && http.responseText.indexOf("User Not Found") < 0 && http.responseText.indexOf("Unauthroized") < 0){
                window.localStorage["token"] = http.responseText;
                console.log("Done: " + window.localStorage["token"]);    
                var vs = chrome.extension.getViews();
				for ( i = 0; i < vs.length; i++) {
					try{
						vs[i].loggedOrNot();
					} catch (err) {
						console.log(err);
					}
				}
				startPollTimers();
				return;
            }
        }
		if (http.readyState == 4) {
			var vs = chrome.extension.getViews();
			for ( i = 0; i < vs.length; i++) {
				try{
					vs[i].displayErrorMsg(http);
				} catch (err) {
					console.log(err);
				}
			}
				
		}
    } // end callable function
	
    http.send(params);
    return false;
}

clearDesktopNotification = function (notification) {
	notification.cancel();
}

displayGrade = function (grade) {
	if (!grade || !settings["gradeNotification"]) {
		return;
	}
	
	gradeDesktopNotification = webkitNotifications.createNotification(
		'/images/guc.png',  // icon url - can be relative
		"Grade Added in " +
		(grade.attributes["course_code"]? grade.attributes["course_code"].value + ": " : "") + 
		grade.attributes["element_type"].value,  // element type
		"You got: " + grade.attributes["scored_grade"].value + "/" + grade.attributes["full_grade"].value
	);
	gradeDesktopNotification.show();
	setTimeout("clearDesktopNotification(gradeDesktopNotification)", settings["notificationTime"]);
	console.log("grade desktop notification was showed");
}
displayNotification = function (notification) {
	if (!notification
	|| (!settings["notificationNotification"] && notification.attributes["notification_type"].value.toLowerCase() != "broadcast")
	|| (!settings["broadcastNotification"] && notification.attributes["notification_type"].value.toLowerCase() == "broadcast")) {
		return;
	}
	notificationDesktopNotification = webkitNotifications.createNotification(
		'/images/guc.png',  // icon url - can be relative
		(notification.attributes["course_code"]? notification.attributes["course_code"].value + ": " : "") + notification.attributes["notification_title"].value,  // notification title
		notification.attributes["notification_text"].value + "\n" + notification.attributes["notification_date"].value  + "						" +  notification.attributes["notification_type"].value // notification body text
	);
	notificationDesktopNotification.show();
	setTimeout("clearDesktopNotification(notificationDesktopNotification)", settings["notificationTime"]);
	console.log("notification desktop notification was showed");
}

stringifyXML = function (xml) {
	return new XMLSerializer().serializeToString(xml);
}
loadXML = function (txt) {
	txt2 = txt.substr(txt.indexOf("<xs:schema"), txt.indexOf("</xs:schema>"));
	txt = txt.replace(txt2, "").replace("?","");
	return new DOMParser().parseFromString(txt,"text/xml");
}
saveNotifications = function (data) {
	newNotifications = data.getElementsByTagName("Notifications");
	
	lastNotification = Date.parse(newNotifications[newNotifications.length - 1].attributes["notification_date"].value);
	ln = newNotifications[newNotifications.length - 1];
	
	if (localStorage.notifications) {
		localNotifications = loadXML(localStorage.notifications);
		if (parseInt(localStorage.lastChecked, 10) < lastNotification) {
			for (i = 0; i < newNotifications.length ; i++) {
				item = newNotifications[i];
				if ( parseInt(localStorage.lastChecked, 10)  < Date.parse(item.attributes["notification_date"].value) ) {
					localNotifications.documentElement.appendChild(item);
					count ++;
				}
			}
			localStorage.lastChecked = lastNotification;
			console.log(newNotifications);
		} else {
			ln = undefined;
		}
	} else {
		localNotifications = data
		count = newNotifications.length;
	}
	setBadge();
	displayNotification(ln);
	
	localStorage.lastChecked = lastNotification;
	localStorage.notifications = stringifyXML(localNotifications);
}

removeOldGrades = function (oldGrades, newGrades) {
	n = newGrades.getElementsByTagName("Grades");
	o = oldGrades.getElementsByTagName("Grades");
	console.log("n.length == o.length: " + (n.length == o.length));
	for (i = 0; i < o.length; i++) {
	//"course_code,element_name,element_type,scored_grade,full_grade"
		for (j = 0; j < n.length; j++) {
			if (o[i].attributes["course_code"].value == n[j].attributes["course_code"].value
			&& o[i].attributes["element_name"].value == n[j].attributes["element_name"].value
			&& o[i].attributes["element_type"].value == n[j].attributes["element_type"].value
			&& o[i].attributes["scored_grade"].value == n[j].attributes["scored_grade"].value
			&& o[i].attributes["full_grade"].value == n[j].attributes["full_grade"].value) {
				n[j].parentNode.removeChild(n[j]);
				break;
			}
		}
	}
	return n;
}
/*
newGrades is list of items
data is the document;
*/
saveGrades = function (data) {
	if (localStorage.grades) {
		localGrades = loadXML(localStorage.grades);
		data = loadXML(stringifyXML(data));
		newGrades = removeOldGrades(localGrades, data);
		displayGrade(newGrades[newGrades.length - 1]);
		count += newGrades.length;
		for (i = 0; i < newGrades.length; i++) {
			item = newGrades[i]
			localGrades.documentElement.appendChild(item);
		}
	} else {
		newGrades = data.getElementsByTagName("Grades");
		displayGrade(newGrades[newGrades.length - 1]);
		count += newGrades.length;
		localGrades = data
	}
	setBadge()
	localStorage.grades = stringifyXML(localGrades);
}
updatePopUp = function () {
try{
	if (count > 0) {
		var vs = chrome.extension.getViews();
		for ( i = 0; i < vs.length; i++) {
			try{
				if (!vs[i].isSearching) {
					vs[i].loggedOrNot();
				}
			} catch (err) {
				console.log(err);
			}
		}
	}
} catch (err) {
	console.log(err);
}
}
getGrades = function (isDataReady, data) {
	if (!isDataReady) {
		getData ("Grades", "course_code,element_name,element_type,scored_grade,full_grade", getGrades);
		return ;
	} else if (!data) {
		gradesPollTimer = setTimeout(getGrades,settings["pollingTime"]);
		return;
	}
	console.log("Grades data is ready");
	saveGrades(data);
	gradesPollTimer = setTimeout(getGrades, settings["pollingTime"]);
	updatePopUp()
}

getTranscriptGrades = function(isDataReady, data) {
	if (!isDataReady) {
		getData("TranscriptGrades", "course_title,semester_name,semester_year,numeric_gpa,alpha_gpa,credit_hour", getTranscriptGrades);
		return ;
	}
	console.log("data is ready");
}

getNotifications = function (isDataReady, data) {
	if (!isDataReady) {
		getData ("Notifications", "notification_title,notification_text,notification_read,course_code,notification_type,notification_date", getNotifications);
		return ;
	} else if (!data) {
		notificationsPollTimer = setTimeout(getNotifications, settings["pollingTime"]);
		return;
	}
	console.log("Notification data is ready");
	saveNotifications(data);
	notificationsPollTimer = setTimeout(getNotifications, settings["pollingTime"]);
	updatePopUp();
}

getData = function (entity, selectors, callable) {
	var http = new XMLHttpRequest();
	var url = "http://iportal.g-beehive.com/API/GET.aspx?";
	if (!localStorage.token) {
		console.log("No Tokens");
		pollStarted = false;
		return ;
	} else {
		console.log("token is available");
	}
	console.log("Token: " + window.localStorage['token']);
	params = "client_id=3&token=" + encodeURIComponent(window.localStorage["token"]) + "&entity=" + entity + "&selectors="+selectors;
	http.open("GET", url + params, true);
	http.onreadystatechange = function() {//Call a function when the state changes.
		if(http.readyState == 4 && http.status == 200) {
			console.log(http.responseXML);
			callable(true, http.responseXML);
		} else if (http.readyState == 4) {
			callable(true, false);
		}
	}//end callable
	http.send(params);
}


console.log("here we start");

startPollTimers = function () {
	if (!pollStarted) {
		pollStarted = true;
		getNotifications();
		getGrades();
	}
}
clearPollTimers = function () {
	if (pollStarted) {
		clearTimeout(gradesPollTimer);
		clearTimeout(notificationsPollTimer);
		pollStarted = false;
	}
}
startPollTimers();
if(!localStorage.didRun) {
	localStorage.notification_notification = "1";
	localStorage.grade_notification = "1";
	localStorage.broadcast_notification = "1";
	localStorage.notification_time = "10";
	localStorage.didRun = "1";
}